package com.zhiwang.xiaoqu.ui

import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.*
import android.provider.MediaStore
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.view.View
import android.view.WindowManager
import android.webkit.*
import android.widget.Toast
import androidx.annotation.MenuRes
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.tencent.bugly.crashreport.CrashReport
import com.zhiwang.xiaoqu.BuildConfig
import com.zhiwang.xiaoqu.R
import com.zhiwang.xiaoqu.aop.NetWorkRequired
import com.zhiwang.xiaoqu.bus.AppDownLoadProgressEvent
import com.zhiwang.xiaoqu.download.FileDownLoadManager
import com.zhiwang.xiaoqu.ktextension.setImmersive
import com.zhiwang.xiaoqu.mvp.model.sharepref.PrefManager
import com.zhiwang.xiaoqu.ui.about.ServiceActivity
import com.zhiwang.xiaoqu.ui.coupon.DailyCheckInActivity
import com.zhiwang.xiaoqu.util.AppDetector
import com.zhiwang.xiaoqu.widget.Toasty
import copy
import io.reactivex.disposables.Disposable
import kotlinx.android.synthetic.main.activity_web_view.*
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import quickStartActivity
import setGone
import suicideAfterTransition


class WebViewActivity : BaseActivity() {

    val TAG = "WebViewActivity"

    //默认是使用顶部的标题栏，特殊的全屏页面需要使用透明标题栏

    companion object {

        @NetWorkRequired
        fun load(context: Context, url: String) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            context.startActivity(intent)
        }


        @NetWorkRequired
        fun load(context: Context, url: String, needTitle: Boolean) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            intent.putExtra("KEY_TITLE", needTitle)
            context.startActivity(intent)
        }

        @NetWorkRequired
        fun load(context: Context, url: String, needTitle: Boolean, transparent: Boolean = false) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            intent.putExtra("KEY_TITLE", needTitle)
            intent.putExtra("KEY_TRANSPARENT_TITLE", transparent)
            context.startActivity(intent)
        }


        @NetWorkRequired
        fun loadImmersive(context: Context, url: String) {
            val intent = Intent(context, WebViewActivity::class.java)
            intent.putExtra("KEY_URL", url)
            intent.putExtra("KEY_IMMERSIVE", true)
            context.startActivity(intent)
        }
    }

    private val PHOTO_PICK_REQUEST_CODE: Int = 114
    private val REQUEST_PERMISSION_WRITE_STORAGE: Int = 113
    var filePathCallback: ValueCallback<Array<Uri>>? = null

    //初始url
    private lateinit var url: String
    private var needTitle: Boolean = true  //默认的toolbar title
    private var needImmersive = false
    private var transparentTitle = false //透明 Title;有些全屏页面需要背景透明的 Title

    @MenuRes
    private var menuId: Int = R.menu.service_menu_dark

    //保存每次页面跳转之后的url
    private lateinit var currUrl: String
    private lateinit var appName: String

    fun getAjaxString() = "javascript:" +
            "\$.ajaxSetup({\n" +
            "            headers: {\n" +
            "                \"appdevice\": \'android\',\n" +
            "                \"apptoken\": \'${getAppToken()}\'\n" +
            "            }\n" +
            "        });\n"

    fun getAppToken() = PrefManager.token()

    private val webViewClient: WebViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView?, url: String?) {
            val ajaxString = getAjaxString()
            view!!.loadUrl(ajaxString)
            toolbar.title = view.title.toString()
            header_toolbar.title = view.title.toString()
            swipeRefreshLayout.finishRefresh()
        }

        override fun shouldOverrideUrlLoading(view: WebView?, request: WebResourceRequest?): Boolean {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                if (request != null) {
                    if (Uri.parse(request.url.toString())?.scheme!!.contains("http").not()) return true

                    currUrl = request.url.toString()
                }
                view?.loadUrl(
                    request?.url.toString(),
                    mapOf(
                        Pair("appdevice", "android")
                        , Pair("apptoken", PrefManager.token())
                        , Pair("appversion", BuildConfig.VERSION_CODE.toString())
                    )
                )
//                Log.i(TAG, "shouldOverrideUrlLoading: $currUrl")

                return true
            }
            return super.shouldOverrideUrlLoading(view, request)
        }

        @Suppress("OverridingDeprecatedMember")
        override fun shouldOverrideUrlLoading(view: WebView?, url: String?): Boolean {


            if (url != null) {
                currUrl = url
                if (Uri.parse(url).scheme.contains("http").not()) return true
            }
            view?.loadUrl(
                url,
                mapOf(
                    Pair("appdevice", "android"),
                    Pair("apptoken", PrefManager.token()),
                    Pair("appversion", BuildConfig.VERSION_CODE.toString())
                )
            )
            return true
        }

    }

    private val webChromeClient1: WebChromeClient = object : WebChromeClient() {
        override fun onProgressChanged(view: WebView?, newProgress: Int) {
            super.onProgressChanged(view, newProgress)
            if (newProgress >= 100)
                swipeRefreshLayout.finishRefresh()
        }


        override fun onShowFileChooser(
            webView: WebView?,
            filePathCallback: ValueCallback<Array<Uri>>?,
            fileChooserParams: FileChooserParams?
        ): Boolean {

            this@WebViewActivity.filePathCallback = filePathCallback
            if (ContextCompat.checkSelfPermission(
                    this@WebViewActivity,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
                ) == PackageManager.PERMISSION_GRANTED
            ) {
                startActivityForResult(galleryIntent(), PHOTO_PICK_REQUEST_CODE)
            } else {
                ActivityCompat.requestPermissions(
                    this@WebViewActivity,
                    arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE),
                    REQUEST_PERMISSION_WRITE_STORAGE
                )
            }
            return true

        }

        override fun onConsoleMessage(consoleMessage: ConsoleMessage?): Boolean {
            if (BuildConfig.DEBUG)
                Log.i(
                    TAG,
                    "onConsoleMessage: ${consoleMessage!!.message()}  ${consoleMessage!!.lineNumber()}"
                )
            return super.onConsoleMessage(consoleMessage)
        }


    }

    private fun galleryIntent(): Intent {
        val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        return intent
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        window.setImmersive(Color.TRANSPARENT, true)

        setContentView(R.layout.activity_web_view)
        initWebView()
        url = intent.getStringExtra("KEY_URL")
        currUrl = url
        needTitle = intent.getBooleanExtra("KEY_TITLE", true)
        needImmersive = intent.getBooleanExtra("KEY_IMMERSIVE", false)
        transparentTitle = intent.getBooleanExtra("KEY_TRANSPARENT_TITLE", false)

        if (transparentTitle) {//透明标题栏，那么隐藏AppBarLayout ToolBar
            appbar_layout.visibility = View.GONE
            toolbar.visibility = View.VISIBLE
            setSupportActionBar(toolbar)
        } else {
            //不需要透明标题栏，并且也不需要 title ,则全部隐藏如果不需要 title,则
            fl_title.setGone()
            if (!needTitle)
                appbar_layout.visibility = View.GONE
            else setSupportActionBar(header_toolbar)
        }

        //针对水滴屏（刘海屏）的全屏处理
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            val lp = window.attributes

            lp.layoutInDisplayCutoutMode = WindowManager.LayoutParams.LAYOUT_IN_DISPLAY_CUTOUT_MODE_SHORT_EDGES
        }

        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        loadUrl()

        swipeRefreshLayout.setOnRefreshListener {
            refresh()
        }

        EventBus.getDefault().register(this)
    }

    private fun loadUrl() {
        masterWebView.webView.loadUrl(
            url, mapOf(
                Pair("appdevice", "android"),
                Pair("userid", PrefManager.getUserId()),
                Pair("apptoken", PrefManager.token()),
                Pair("appversion", BuildConfig.VERSION_CODE.toString())
            )
        )
    }

    @SuppressLint("SetJavaScriptEnabled")
    private fun initWebView() {
        val settings = masterWebView.webView.settings
        settings.javaScriptEnabled = true
        settings.useWideViewPort = true
        settings.domStorageEnabled = true
        settings.cacheMode = WebSettings.LOAD_NO_CACHE
        settings.textZoom = 100
        masterWebView.webView.webViewClient = webViewClient
        val webChromeClient: WebChromeClient = webChromeClient1
        masterWebView.webView.webChromeClient = webChromeClient
        masterWebView.webView.addJavascriptInterface(this, "android")
        CrashReport.setJavascriptMonitor(masterWebView.webView, true)
    }

    override fun onCreateOptionsMenu(menu: Menu?): Boolean {
        menuInflater.inflate(menuId, menu)
        return true
    }


    override fun onOptionsItemSelected(item: MenuItem?): Boolean {

        when (item?.itemId) {
            R.id.give_up_task -> {
                //todo 让h5 刷新页面
            }

            R.id.contact_custom_service -> {
                quickStartActivity(ServiceActivity::class.java)
            }
        }

        return super.onOptionsItemSelected(item)
    }


    @JavascriptInterface
    fun setMenuType(type: String) {

        when (type) {
            "TypeTaskActionMenuLight" -> menuId = R.menu.task_menu
            "TypeTaskActionMenuDark" -> menuId = R.menu.task_menu_dark
            "TypeServiceActionLight" -> menuId = R.menu.service_menu
            "TypeServiceActionDark" -> menuId = R.menu.service_menu_dark
        }

        invalidateOptionsMenu()
    }

    @JavascriptInterface
    fun claimSecretTask() {
        quickStartActivity(DailyCheckInActivity::class.java)
    }


    @JavascriptInterface
    fun refresh() {
        runOnUiThread {
            swipeRefreshLayout.autoRefresh()
            loadUrl()
        }
    }


    @JavascriptInterface
    fun setRefreshEnabled(enable: String) {
        when (enable) {
            "true" -> swipeRefreshLayout.setEnableRefresh(true)
            "false" -> swipeRefreshLayout.setEnableRefresh(false)
        }
    }


    @JavascriptInterface
    fun showPhotoView(url: String) {
        PhotoPreviewActivity.load(this, url)
    }


    @JavascriptInterface
    fun copyToClipBoard(text: String) {
        copy(text)
        runOnUiThread {
            Toasty.message("复制成功")
        }
    }

    @JavascriptInterface
    fun launchApp(packageName: String) {
        val intentForPackage = packageManager.getLaunchIntentForPackage(packageName)
        if (intentForPackage == null)
        else {
            intentForPackage.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            startActivity(intentForPackage)
        }
    }

    @JavascriptInterface
    fun setAppName(appName: String) {
        this.appName = appName
    }


    @JavascriptInterface
    fun downloadAPP(url: String) {
        //如果系统下载被禁用，那么使用备用下载
//        if (isDownloadManagerAvailable(this))
//            runOnUiThread {
//                GameApkDownLoadService.start(this, url, appName)
//            }
//        else {
//            DownLoadManager.create(this).downLoadFileBackground(url, appName)
//        }
        //现在 使用FileDownLoader 下载，部分机型上下载器可能无法使用，并且上面的代码无法准确判断下载器是否可用
        FileDownLoadManager.download(
            url, appName,
            getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS)?.absolutePath
                ?: Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS).absolutePath
        )
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onAppDownloadProgress(event: AppDownLoadProgressEvent) {
        masterWebView.webView?.loadUrl("javascript:downloadGame(\'${event.progress}\',\'${event.name}\')")
    }

    @JavascriptInterface
    fun isAppInstalled(packageName: String): String {
        var installed = "false"
        try {
            packageManager.getPackageInfo(packageName, 0)
            installed = "true"
        } catch (e: PackageManager.NameNotFoundException) {
            Toasty.message("未安装应用$packageName")
        }
        return installed
    }

    @JavascriptInterface
    fun openLink(url: String, isExternal: String) {
        when (isExternal) {
            "false" -> load(this, url)
            "true" -> {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse(url))
                startActivity(intent)
            }
        }
    }

    @JavascriptInterface
    fun openLinkWithoutTitle(url: String) {
        load(this, url, false)
    }


    @JavascriptInterface
    fun getAppDownloadProgress(appName: String): String {
        return FileDownLoadManager.getAppDownloadProgress(appName)
    }

    @JavascriptInterface
    fun close() {
        suicideAfterTransition()
    }

    @JavascriptInterface
    fun requestLogin() {
        PrefManager.clearToken()
        LoginActivity.start(this)
        suicideAfterTransition()
    }


    override fun onSupportNavigateUp(): Boolean {
        onBackPressed()
        return true
    }


    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == PHOTO_PICK_REQUEST_CODE && data != null) {
            filePathCallback?.onReceiveValue(arrayOf(data.data))
            return
        }
        filePathCallback?.onReceiveValue(null)
        super.onActivityResult(requestCode, resultCode, data)
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        if (requestCode == REQUEST_PERMISSION_WRITE_STORAGE && grantResults[0] == PackageManager.PERMISSION_GRANTED)
            startActivityForResult(galleryIntent(), PHOTO_PICK_REQUEST_CODE)
    }


    var targetPackageName = "com.zhiwang.planet"

    var requesting = false

    var timePassed = 0

    var targetUsageTime = 0

    var disposable: Disposable? = null

    var targetFound = false

    var taskCompleted = false


    override fun onResume() {
        super.onResume()

        //todo 开启 查询App 使用情况权限
/*        if (AppDetector.hasAppUsagePermission(this)) {

//            continuouslyDetect(targetPackageName, 20)

        } else {

            if (requesting) {
                Toasty.message("没有权限")
                requesting = false
                return
            }

            Log.i(TAG, "onStart: -----------")
            requesting = true
            startActivity(
                Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS)
            )
        }*/

    }

    fun reset() {
        disposable?.dispose()
        targetFound = false
        timePassed = 0
    }

    private fun continuouslyDetect(pkgName: String, time: Int) {
        reset()
        targetUsageTime = time
        object : CountDownTimer(3600000, 1000) {
            override fun onFinish() {

            }

            override fun onTick(millisUntilFinished: Long) {
                Log.i(TAG, "continuouslyDetect: ----------tick---------------")

                val active = AppDetector.queryAppUsage(this@WebViewActivity, pkgName)

                if (targetFound && active)
                    timePassed += 1

                if (targetFound && active.not() && taskCompleted.not()) {
                    //重置 app 使用时间，必须一次性使用试玩时间
                    timePassed = 0
                    //提示继续玩
                    Toast.makeText(this@WebViewActivity, "试玩时间还没到，再玩一会儿", Toast.LENGTH_SHORT).show()
                }

                if (timePassed >= targetUsageTime && taskCompleted.not()) {
                    //
                    taskCompleted = true
                    cancel()
                    reset()
                    Toast.makeText(this@WebViewActivity, "奖励已经发放", Toast.LENGTH_SHORT).show()
                    Log.i(TAG, "continuouslyDetect: 领取奖励-------------------------------------")
                }

                if (targetFound.not() && active && taskCompleted.not()) {
                    if (timePassed == 0)
                        Toast.makeText(this@WebViewActivity, "请按照要求试玩", Toast.LENGTH_SHORT).show()
                    else
                        Toast.makeText(this@WebViewActivity, "继续试玩才能领取奖励~", Toast.LENGTH_SHORT).show()
                }

                targetFound = active
            }

        }.start()
    }

}
